package com.message.admin.send.task;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.message.admin.send.enums.SendStatus;
import com.message.admin.send.pojo.SendEmail;
import com.message.admin.send.service.SendEmailService;
import com.message.admin.send.utils.SendMailUtil;
import com.ms.env.EnvUtil;
import com.system.comm.utils.FrameJsonUtil;
import com.system.comm.utils.FrameMapUtil;
import com.system.comm.utils.FrameNoUtil;
import com.system.comm.utils.FrameSpringBeanUtil;
import com.system.comm.utils.FrameStringUtil;
import com.system.handle.model.ResponseCode;
import com.system.handle.model.ResponseFrame;

/**
 * 启动线程
 * @author yuejing
 * @date 2016年10月22日 上午9:58:59
 * @version V1.0.0
 */
public class SendEmailTask {

	private static final Logger LOGGER = LoggerFactory.getLogger(SendEmailTask.class);

	private static final int WAIT_NUM = 200;

	public void run(int initialDelay, int period) {
		String servNo = FrameNoUtil.uuid();
		SendEmailService sendEmailService = FrameSpringBeanUtil.getBean(SendEmailService.class);
		ScheduledExecutorService service = new ScheduledThreadPoolExecutor(5, new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
				Thread thread = new Thread(r);
				LOGGER.info("初始发送Email的线程:" + thread.getName());
				return thread;
			}
		});
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				try {
					//修改待发送的邮件为当前服务的
					sendEmailService.updateWaitToIng(servNo, WAIT_NUM);
					List<SendEmail> emails = sendEmailService.findIng(servNo);
					for (SendEmail se : emails) {
						//发送邮件
						deal(se);
					}
				} catch (Exception e) {
					LOGGER.error("处理邮件发送异常: " + e.getMessage(), e);
				}
			}
		};
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间  
		service.scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.SECONDS);
	}
	
	public static void main(String[] args) {
		new SendEmailTask().run(3, 5);
	}

	private void deal(SendEmail sendEmail) {
		SendEmailService sendEmailService = FrameSpringBeanUtil.getBean(SendEmailService.class);
		//调用发送邮件的接口
		ResponseFrame seFrame = sendEmail(sendEmail);
		if(ResponseCode.SUCC.getCode() == seFrame.getCode().intValue()) {
			//发送成功
			sendEmailService.updateStatus(sendEmail.getId(), SendStatus.SUCC.getCode());
			LOGGER.info("Email发送成功! 接收人[" + sendEmail.getEmail() + "]");
		} else {
			//发送失败，等待1s，重发一次
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			seFrame = sendEmail(sendEmail);
			if(ResponseCode.SUCC.getCode() == seFrame.getCode().intValue()) {
				//发送成功
				sendEmailService.updateStatus(sendEmail.getId(), SendStatus.SUCC.getCode());
				LOGGER.info("Email发送成功! 接收人[" + sendEmail.getEmail() + "]");
			} else {
				//发送失败
				sendEmailService.updateStatus(sendEmail.getId(), SendStatus.FAIL.getCode());
				LOGGER.info("Email发送失败! 接收人[" + sendEmail.getEmail() + "]");
			}
		}
	}

	private ResponseFrame sendEmail(SendEmail sendEmail) {
		ResponseFrame frame = new ResponseFrame();
		String content = sendEmail.getContent();
		String title = sendEmail.getTitle();
		/*if(content.length() > 140) {
			title = content.substring(0, 140);
		} else {
			title = content;
		}*/
		//String names = null;
		try {
			String files = null;
			String fileString = sendEmail.getFiles();
			if(FrameStringUtil.isNotEmpty(fileString)) {
				List<Map<String, String>> fileList = FrameJsonUtil.toList(fileString, Map.class);
				if(fileList != null && fileList.size() > 0) {
					//names = "";
					files = "";
					for (Map<String, String> map : fileList) {
						//names += FrameMapUtil.getString(map, "name") + ";";
						files += FrameMapUtil.getString(map, "path") + ";";
					}
				}
			}
			//调用发送email的功能
			SendMailUtil.sendMail(EnvUtil.sendEmailSmtp(), EnvUtil.sendEmailFrom(),
					EnvUtil.sendEmailUsername(), EnvUtil.sendEmailPassword(),
					sendEmail.getEmail(), title, content, files);
			frame.setSucc();
		} catch (Exception e) {
			frame.setCode(-1);
			LOGGER.error(e.getMessage(), e);
		}
		return frame;
	}
}